from django.shortcuts import render

# Create your views here.

from django.views.decorators.csrf import csrf_exempt

import json


from django.http import HttpResponse, JsonResponse
from django.core.exceptions import ObjectDoesNotExist

from api.utils import success_response_with_data, failed_response_with_data, list_response
from api.utils_material import get_material
from django.conf import settings

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action

from api.models import Pose
from api.serializers import PoseSerializer
from api.mylogger import logger


class PoseViewSet(viewsets.ModelViewSet):
    table_name = Pose._meta.db_table
    serializer_class = PoseSerializer

    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['name', 'posetype', 'humanid'],
                                  properties={
                                      "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
                                      "posetype": openapi.Schema(type=openapi.TYPE_STRING, description="动作类别,不填时为vhuman"),
                                      "humanid": openapi.Schema(type=openapi.TYPE_INTEGER, description="虚拟人Id"),
                                      "status": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="状态(1激活，0禁用)"),
                                  }, )

    @swagger_auto_schema(operation_id='添加动作', tags=['pose'], request_body=request_body)
    @action(methods=['POST'], detail=False)
    def pose_add(self, request):
        data = json.loads(request.body.decode('utf8'))
        serializer = PoseSerializer(data=data)
        if serializer.is_valid():
            res = serializer.save()
            res_data = {
                "table_name": self.table_name,
                "id": res.id,
            }
            return success_response_with_data(res_data, msg="新增动作成功")
        return JsonResponse(serializer.errors, status=400)

    request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
                                      required=['name', 'posetype', 'humanid'],
                                      properties={
                                          "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="内部Id"),
                                          "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
                                          "posetype": openapi.Schema(type=openapi.TYPE_STRING, description="动作类别,不填时为vhuman"),
                                          "humanid": openapi.Schema(type=openapi.TYPE_INTEGER, description="虚拟人Id"),
                                          "status": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="状态(1激活，0禁用)"),
                                      }, )

    @swagger_auto_schema(operation_id='修改动作', tags=['pose'], request_body=request_body_mod)
    @action(methods=['POST'], detail=False)
    def pose_mod(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        if db_id is None:
            return failed_response_with_data(msg="没有id, 修改不了")

        serializer = PoseSerializer(data=data)
        if serializer.is_valid():
            try:
                db_ret = serializer.update(instance=Pose.objects.get(id=db_id), validated_data=data)
                res_data = {
                    "table_name": self.table_name,
                    "id": db_ret.id
                }
                return success_response_with_data(res_data, msg="修改动作成功!")
            except ObjectDoesNotExist:
                logger.debug("没有修改记录")
                return failed_response_with_data(msg=self.table_name + f"没有被修改,未发现id为{db_id}的记录")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='删除动作', tags=['pose'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="动作表的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def pose_del(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        # qry = Material.objects.filter(id=db_id)
        # print(qry.query)
        deleted_cnt, _ = Pose.objects.filter(id=db_id).delete()
        res_data = {
            "table_name": self.table_name,
            "id": db_id,
            "rows_deleted": deleted_cnt,
            "info": "删除" + str(deleted_cnt) + "条记录!",
        }
        return success_response_with_data(res_data, msg="删除横幅记录成功!")

    @swagger_auto_schema(operation_id='查询动作', tags=['pose'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "human_id": openapi.Schema(type=openapi.TYPE_INTEGER, description="所属虚拟人"),
            "query": openapi.Schema(type=openapi.TYPE_STRING, description="动作名"),
            "posetype": openapi.Schema(type=openapi.TYPE_STRING, description="类别"),
            "pagenum": openapi.Schema(type=openapi.TYPE_INTEGER, description="页号"),
            "pagesize": openapi.Schema(type=openapi.TYPE_INTEGER, description="记录条数"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def pose_list(self, request):
        data = json.loads(request.body.decode('utf8'))
        current_page = data.get("pagenum", 1)
        page_size = data.get("pagesize", 10)
        human_id = data.get("human_id", 0)
        query = data.get("query", '')
        posetype = data.get("posetype", '')

        if current_page < 1:
            current_page = 1
        if page_size < 1:
            page_size = 10

        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = Pose.objects
            if posetype != '':
                objects = objects.filter(posetype=posetype)
            if human_id != 0:
                objects = objects.filter(human_id=human_id)

            if len(query):
                objects = objects.filter(name__icontains=query)
            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")

        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        # serializer = PoseSerializer(rows, many=True)
        # return list_response(serializer.data, total, page_size, current_page, self.table_name)

        pose_list = PoseSerializer(rows, many=True).data

        for index in range(len(pose_list)):
            row = pose_list[index]
            human_id = row["human_id"]
            row["pose_id"] = row["id"]
            row["vhuman"] = get_material(human_id)

        return list_response(pose_list, total, page_size, current_page, self.table_name)

